<template>
  <div class="login-view">
    <div class="auth-container">
      <div class="logo-container">
        <h1 class="logo">法律AI助手</h1>
        <p class="subtitle">专业法律问题解答与案例检索</p>
      </div>
      
      <div class="tabs">
        <div 
          class="tab" 
          :class="{ active: activeTab === 'login' }"
          @click="setActiveTab('login')"
        >
          登录
        </div>
        <div 
          class="tab" 
          :class="{ active: activeTab === 'register' }"
          @click="setActiveTab('register')"
        >
          注册
        </div>
      </div>
      
      <!-- 登录表单 -->
      <form 
        v-if="activeTab === 'login'" 
        class="auth-form" 
        @submit.prevent="handleLogin"
      >
        <div class="form-group">
          <label for="login-username">用户名</label>
          <input 
            type="text" 
            id="login-username" 
            v-model="loginForm.username"
            placeholder="请输入用户名" 
            required
          />
        </div>
        
        <div class="form-group">
          <label for="login-password">密码</label>
          <input 
            type="password" 
            id="login-password" 
            v-model="loginForm.password"
            placeholder="请输入密码" 
            required
          />
        </div>
        
        <div v-if="loginError" class="error-message">
          {{ loginError }}
        </div>
        
        <button 
          type="submit" 
          class="primary-button"
          :disabled="isProcessing"
        >
          {{ isProcessing ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <!-- 注册表单 -->
      <form 
        v-else 
        class="auth-form" 
        @submit.prevent="handleRegister"
      >
        <div class="form-group">
          <label for="register-username">用户名</label>
          <input 
            type="text" 
            id="register-username" 
            v-model="registerForm.username"
            placeholder="请输入用户名（3-20个字符）" 
            required
            minlength="3"
            maxlength="20"
          />
        </div>
        
        <div class="form-group">
          <label for="register-password">密码</label>
          <input 
            type="password" 
            id="register-password" 
            v-model="registerForm.password"
            placeholder="请输入密码（至少6位）" 
            required
            minlength="6"
          />
        </div>
        
        <div class="form-group">
          <label for="register-confirm">确认密码</label>
          <input 
            type="password" 
            id="register-confirm" 
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码" 
            required
          />
        </div>
        
        <div v-if="registerError" class="error-message">
          {{ registerError }}
        </div>
        
        <button 
          type="submit" 
          class="primary-button"
          :disabled="isProcessing"
        >
          {{ isProcessing ? '注册中...' : '注册' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { login, register } from '@/services/auth';

export default {
  name: 'LoginView',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const activeTab = ref('login');
    const isProcessing = ref(false);
    
    // 登录表单
    const loginForm = ref({
      username: '',
      password: '',
    });
    const loginError = ref('');
    
    // 注册表单
    const registerForm = ref({
      username: '',
      password: '',
      confirmPassword: '',
    });
    const registerError = ref('');
    
    // 设置活动标签
    const setActiveTab = (tab) => {
      activeTab.value = tab;
      loginError.value = '';
      registerError.value = '';
    };
    
    // 处理登录
    const handleLogin = async () => {
      loginError.value = '';
      
      // 验证表单
      if (!loginForm.value.username || !loginForm.value.password) {
        loginError.value = '请输入用户名和密码';
        return;
      }
      
      isProcessing.value = true;
      
      try {
        const result = login(
          loginForm.value.username, 
          loginForm.value.password
        );
        
        if (result.success) {
          // 登录成功，初始化用户数据
          store.dispatch('initAuth');
          
          // 检查是否有重定向URL
          const redirectPath = route.query.redirect || '/';
          // 跳转到首页或重定向URL
          router.push(redirectPath);
        } else {
          loginError.value = result.message;
        }
      } catch (error) {
        console.error('登录过程中出错:', error);
        loginError.value = '登录失败，请稍后重试';
      } finally {
        isProcessing.value = false;
      }
    };
    
    // 处理注册
    const handleRegister = async () => {
      registerError.value = '';
      
      // 验证表单
      if (!registerForm.value.username || !registerForm.value.password) {
        registerError.value = '请输入用户名和密码';
        return;
      }
      
      if (registerForm.value.username.length < 3) {
        registerError.value = '用户名至少需要3个字符';
        return;
      }
      
      if (registerForm.value.password.length < 6) {
        registerError.value = '密码至少需要6个字符';
        return;
      }
      
      if (registerForm.value.password !== registerForm.value.confirmPassword) {
        registerError.value = '两次输入的密码不一致';
        return;
      }
      
      isProcessing.value = true;
      
      try {
        const result = register(
          registerForm.value.username, 
          registerForm.value.password
        );
        
        if (result.success) {
          // 注册成功，初始化用户数据
          store.dispatch('initAuth');
          
          // 跳转到首页
          router.push('/');
        } else {
          registerError.value = result.message;
        }
      } catch (error) {
        console.error('注册过程中出错:', error);
        registerError.value = '注册失败，请稍后重试';
      } finally {
        isProcessing.value = false;
      }
    };
    
    return {
      activeTab,
      loginForm,
      registerForm,
      loginError,
      registerError,
      isProcessing,
      setActiveTab,
      handleLogin,
      handleRegister
    };
  }
}
</script>

<style scoped>
.login-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f9fafb;
}

.auth-container {
  width: 100%;
  max-width: 420px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  transition: all 0.3s ease;
}

.logo-container {
  text-align: center;
  margin-bottom: 2rem;
}

.logo {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary-color);
  margin-bottom: 0.5rem;
}

.subtitle {
  color: #6b7280;
  font-size: 1rem;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 1.5rem;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 0.75rem 0;
  font-weight: 500;
  color: #6b7280;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab:hover {
  color: var(--primary-color);
}

.tab.active {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-size: 0.9rem;
  font-weight: 500;
  color: #374151;
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(16, 163, 127, 0.2);
}

.error-message {
  background-color: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  padding: 0.75rem;
  border-radius: 6px;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

.primary-button {
  margin-top: 1rem;
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 0.85rem;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.primary-button:hover {
  background-color: #0d926f;
}

.primary-button:disabled {
  background-color: #94d3c4;
  cursor: not-allowed;
}

@media (max-width: 480px) {
  .auth-container {
    max-width: 90%;
    padding: 1.5rem;
  }
}
</style>